import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:hive/hive.dart';
import 'package:ichinesereader/pages/book/bookQuizReviewer.dart';
import 'package:ichinesereader/utils/helper.dart';
import 'package:ichinesereader/models/book/BookArguments.dart';
import 'package:ichinesereader/constants.dart';
import 'package:ichinesereader/models/book/ProgramBookLists.dart';
import 'package:ichinesereader/models/book/BookItem.dart';
import 'package:ichinesereader/utils/log.dart';
import 'package:ichinesereader/controller/cache.dart';

// ignore: must_be_immutable
class TextbookGrid extends StatefulWidget {
  TextbookGrid({
    Key? key,
    required this.categories,
    required this.selected,
    //required this.selectedBooks,
    required this.onChanged,
    required this.onChanged2,
  }) : super(key: key);

  List<ProgramBookList> categories;
  final List<String> selected;
  final ValueChanged<List<String>> onChanged;
  final ValueChanged<List<BookItem>> onChanged2;

  @override
  _TextbookGrid createState() => _TextbookGrid();
}

class _TextbookGrid extends State<TextbookGrid>
    with SingleTickerProviderStateMixin {
  List<String> _selected = [];
  List<BookItem> _selectedBooklist = [];
  void _handleSelectChanged(List<String> newValue) {
    setState(() {
      _selected = newValue;
      widget.onChanged(newValue);
    });
  }

  void _handleSelectChanged2(List<BookItem> newValue) {
    setState(() {
      _selectedBooklist = newValue;
      widget.onChanged2(newValue);
    });
  }

  @override
  Widget build(BuildContext context) {
    Log.debug('start building TextbookGrid program books');
    Log.debug(widget.categories.length);
    Log.debug(widget.categories[0].lowerProgram!.length);
    return GridView.builder(
        gridDelegate: const SliverGridDelegateWithMaxCrossAxisExtent(
            maxCrossAxisExtent: 800,
            crossAxisSpacing: 50,
            //width:height
            childAspectRatio: 0.8,
            mainAxisSpacing: 50),
        itemCount: widget.categories.length,
        itemBuilder: (BuildContext ctx, index) {
          // color:
          // index % 2 == 0 ? Colors.cyan : Colors.deepOrange;
          String? topicName = widget.categories[index].name;
          // String? id = widget.categories[index].id;
          List<ProgramBookList>? topicLists =
              widget.categories[index].lowerProgram;
          return Container(
            //color: Colors.white30,
            child: ListView(
              shrinkWrap: true,
              primary: false,
              children: [
                SizedBox(
                  height: 20,
                ),
                Center(
                  child: Text(topicName!,
                      style: TextStyle(
                          color: Colors.red,
                          fontSize: 20,
                          fontWeight: FontWeight.bold)
                      //style: Theme.of(context).textTheme.headline4,
                      ),
                ),
                SizedBox(
                  height: 20,
                ),
                if (topicLists != null && topicLists.length > 0)
                  ...getTopics1(
                      topicLists,
                      _selected,
                      _handleSelectChanged,
                      _selectedBooklist,
                      _handleSelectChanged2,
                      context,
                      setState)
              ],
            ),
            decoration: BoxDecoration(
                color: Color.fromARGB(213, 240, 245, 245),
                borderRadius: BorderRadius.circular(15)),
          );
        });
  }
}

List<Widget> getTopics1(contents, selected, _handleSelectChanged,
    _selectedBooklist, _handleSelectChanged2, context, setState) {
  List<Widget> data = [];
  //bool quizAvailable = true;
  for (var i = 0; i < contents.length; i++) {
    //String? id = contents[i].id;
    String? topicName = contents[i].name;
    List<ProgramBookList>? topicLists = contents[i].lowerProgram;

    data.add(new ExpansionTile(
      //initiallyExpanded: false,
      title: Text(topicName!, style: TextStyle(color: Colors.black)
          // style: Theme.of(context).textTheme.headline5,
          ),
      children: <Widget>[
        if (topicLists != null && topicLists.length > 0)
          ...getTopics2(topicLists, selected, _handleSelectChanged,
              _selectedBooklist, _handleSelectChanged2, context, setState)
        else if (contents[i].lowerProgram == null &&
            contents[i].bookList.length > 0)
          ...getBooks(contents[i].bookList, selected, _handleSelectChanged,
              _selectedBooklist, _handleSelectChanged2, context, setState)
      ],
    ));
  }
  return data;
}

List<Widget> getTopics2(contents, selected, _handleSelectChanged,
    _selectedBooklist, _handleSelectChanged2, context, setState) {
  List<Widget> data = [];
  for (var i = 0; i < contents.length; i++) {
    //String? id = contents[i].id;
    String? topicName = contents[i].name;
    List<ProgramBookList>? topicLists = contents[i].lowerProgram;
    data.add(new ExpansionTile(
      title: Text(
        topicName!,
        style: TextStyle(color: Color.fromARGB(227, 192, 145, 6)),
      ),
      children: <Widget>[
        if (contents[i].lowerProgram == null && contents[i].bookList.length > 0)
          ...getBooks(contents[i].bookList, selected, _handleSelectChanged,
              _selectedBooklist, _handleSelectChanged2, context, setState)
        else if (topicLists != null && topicLists.length > 0)
          ...getTopics3(topicLists, selected, _handleSelectChanged,
              _selectedBooklist, _handleSelectChanged2, context, setState)
      ],
    ));
  }
  return data;
}

List<Widget> getTopics3(contents, selected, _handleSelectChanged,
    _selectedBooklist, _handleSelectChanged2, context, setState) {
  List<Widget> data = [];
  for (var i = 0; i < contents.length; i++) {
    //String? id = contents[i].id;
    String? topicName = contents[i].name;
    data.add(new ExpansionTile(
      title: Text(
        topicName!,
        style: TextStyle(color: Color.fromARGB(255, 4, 103, 168)),
        // style: Theme.of(context).textTheme.headline5,
      ),
      children: <Widget>[
        if (contents[i].bookList != null && contents[i].bookList.length > 0)
          ...getBooks(contents[i].bookList, selected, _handleSelectChanged,
              _selectedBooklist, _handleSelectChanged2, context, setState)
      ],
    ));
  }
  return data;
}

List<Widget> getBooks(bookList, selected, _handleSelectChanged,
    _selectedBooklist, _handleSelectChanged2, context, setState) {
  List<Widget> data = [];
  final box = Hive.box('appconfig');

  for (var i = 0; i < bookList.length; i++) {
    String bid = bookList[i].bookId ?? '';
    String btitle = bookList[i].bookTitle ?? '';
    String bcode = bookList[i].bookCode ?? '';
    bool quizAvailable = bookList[i].quizAvailable ?? false;
    bool inFolder = bookList[i].inFolder ?? false;

    data.add(
      Padding(
        padding: EdgeInsets.symmetric(vertical: 0.0, horizontal: 15.0),
        child: new Row(
          children: [
            new GestureDetector(
              onTap: () {
                if ((GetPlatform.isDesktop || GetPlatform.isMacOS) &&
                    !GetPlatform.isWeb) {
                  launchInWebViewWithJavaScript(
                      '${Constants.BaseURL}icr/student/book/$bid');
                } else if (GetPlatform.isWeb) {
                  launchInWebViewWithJavaScript(
                      '${Constants.BaseURL}icr/student/book/$bid');
                  // Navigator.pushNamed(context, '/student/book',
                  //     arguments: BookArguments(bid, bcode, btitle, null,
                  //         NanhaiBookReadingTypes.textbook, null));
                } else {
                  String viewMode = bookList[i].viewMode ?? 'LANDSCAPE';
                  box.put(CacheManagerKey['_viewMode'].toString(), viewMode);
                  Navigator.pushNamed(context, '/student/book',
                      arguments: BookArguments(bid, bcode, btitle, null,
                          NanhaiBookReadingTypes.textbook, null));
                }
              },
              child: Center(
                child: Text(bookList[i].bookTitle),
              ),
            ),
            SizedBox(width: 10.0),
            Expanded(child: Text('')),
            Padding(
              padding: const EdgeInsets.only(left: 22.0),
            ),
            if (quizAvailable)
              new GestureDetector(
                onTap: () {
                  Get.to(() => BookQuizReviewer(
                        bookId: bid,
                        bookTitle: btitle,
                      ));
                },
                child: Icon(Icons.quiz_outlined,
                    size: 22, color: Theme.of(context).primaryColorDark),
              ),
            Padding(
              padding: const EdgeInsets.only(left: 10.0),
            ),
            // new GestureDetector(
            //   onTap: () {},
            //   child: Icon(Icons.search, size: 22),
            // ),
            // SizedBox(width: 10.0),
            Icon(Icons.favorite_border_rounded,
                size: 22,
                color: inFolder ? hexStringToHexInt('#ffc107') : Colors.grey),
            Padding(
              padding: const EdgeInsets.only(left: 10.0),
            ),
            Checkbox(
                value: selected.contains(bid),
                onChanged: (bool? value) {
                  if (selected.contains(bid)) {
                    selected.removeWhere((str) {
                      return str == bid;
                    });
                    _selectedBooklist.removeWhere((item) => item.bookId == bid);
                  } else {
                    selected.add(bid);
                    BookItem item = new BookItem();
                    item.bookId = bookList[i].bookId;
                    item.bookTitle = bookList[i].bookTitle;
                    _selectedBooklist.add(item);
                  }
                  _handleSelectChanged(selected);
                  _handleSelectChanged2(_selectedBooklist);
                }),
          ],
        ),
      ),
    );
  }
  return data;
}
